package com.yupi.yupicturebackend.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.common.UserHolder;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.UserLoginDTO;
import com.yupi.yupicturebackend.model.dto.UserRegisterDTO;
import com.yupi.yupicturebackend.model.dto.user.UserAddDTO;
import com.yupi.yupicturebackend.model.dto.user.UserQueryDTO;
import com.yupi.yupicturebackend.model.dto.user.UserUpdateDTO;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.vo.UserVO;
import com.yupi.yupicturebackend.service.UserService;
import io.swagger.annotations.ApiOperation;
import lombok.experimental.WithBy;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterDTO userRegisterDTO) {
        ThrowUtils.throwIf(userRegisterDTO == null, ErrorCode.PARAMS_ERROR);
        String userPassword = userRegisterDTO.getUserPassword();
        String userAccount = userRegisterDTO.getUserAccount();
        String checkPassword = userRegisterDTO.getCheckPassword();
        Long l = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(l);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public BaseResponse userLogin(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest httpRequest) {
        ThrowUtils.throwIf(userLoginDTO == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginDTO.getUserAccount();
        String userPassword = userLoginDTO.getUserPassword();
        UserVO userVO = userService.userLogin(userAccount, userPassword, httpRequest);
        return ResultUtils.success(userVO);
    }

    @ApiOperation("获取当前登录用户")
    @GetMapping("/me")
    public BaseResponse getUser() {
        UserVO user = UserHolder.getUser();
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return ResultUtils.success(user);
    }

    @PutMapping("/logout")
    @ApiOperation("用户退出")
    public BaseResponse userLogout(HttpServletRequest httpRequset) {
        UserVO userLogin = UserHolder.getUser();
        if (userLogin == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "当前用户未登录");
        }
        httpRequset.getSession().removeAttribute("user_login");
        UserHolder.removeUser();
        return ResultUtils.success();
    }
    //-------------------------------------------------------------------------

    @PostMapping("/add")
    @ApiOperation("管理员创建用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddDTO userAddDTO) {
        ThrowUtils.throwIf(userAddDTO == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(userAddDTO, user);
        //默认密码是12345678
        String password = DigestUtil.md5Hex("12345678");
        user.setUserPassword(password);
        boolean save = userService.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    @GetMapping("/get/{id}")
    @ApiOperation("管理员查询用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(@PathVariable long id) {
        User byId = userService.getById(id);
        ThrowUtils.throwIf(byId == null, ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(byId);
    }

    @GetMapping("/get/vo")
    @ApiOperation("管理员查询脱敏用户")
    public BaseResponse<UserVO> getUserVOById(long id) {
        User byId = userService.getById(id);
        UserVO userVo = new UserVO();
        BeanUtil.copyProperties(byId, userVo);
        return ResultUtils.success(userVo);
    }

    @PostMapping("/delete/{id}")
    @ApiOperation("管理员删除用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@PathVariable Long id) {
        boolean b = userService.removeById(id);
        return ResultUtils.success(b);
    }

    @PostMapping("/update")
    @ApiOperation("管理员更新用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> update(@RequestBody UserUpdateDTO userUpdateDTO) {
        if (userUpdateDTO == null || userUpdateDTO.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtil.copyProperties(userUpdateDTO, user);
        boolean b = userService.updateById(user);
        ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    @PostMapping("/list/page/vo")
    @ApiOperation("管理员查询用户列表")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryDTO userQueryDTO) {
        if (userQueryDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //1.分页参数
        int current = userQueryDTO.getCurrent();
        int pageSize = userQueryDTO.getPageSize();
        //2.分页对象
        Page<User> userPage = new Page<>(current, pageSize);
        //3.分页查询
        Page<User> page = userService.page(userPage);
        //4.总条数
        long total = page.getTotal();
        //5.总页数
        long pages = page.getPages();
        //6.分页数据
        List<User> records = page.getRecords();
        //把user转换成uservo
        List<UserVO> collect = records.stream().map(a -> BeanUtil.copyProperties(a, UserVO.class)).collect(Collectors.toList());
        Page<UserVO> userVOPage = new Page<>(current, pageSize, total);
        userVOPage.setRecords(collect);

        return ResultUtils.success(userVOPage);
    }
}

